<template>
  <div class="table-page">
    <el-card>
      <!-- 顶部操作栏 -->
      <div class="toolbar">
        <el-button @click="showAddCrop" type="primary" icon="Plus"
          >新增</el-button
        >
        <el-select
          v-model="filterCategory"
          placeholder="作物类别"
          style="width: 120px; margin-left: 20px"
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="水果" value="水果"></el-option>
          <el-option label="蔬菜" value="蔬菜"></el-option>
          <el-option label="粮食" value="粮食"></el-option>
        </el-select>
        <el-select
          v-model="filterMature"
          placeholder="成熟状态"
          style="width: 120px; margin-left: 20px"
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="成熟" value="1"></el-option>
          <el-option label="未成熟" value="0"></el-option>
        </el-select>
      </div>
      <!-- 表格 -->
      <el-table
        :data="filteredTableData"
        style="width: 100%; margin-top: 20px"
        ref="tableRef"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="作物名称" />
        <el-table-column prop="cropCategory" label="类别" />
        <el-table-column prop="landName" label="所属土地" />
        <el-table-column prop="price" label="价格" />
        <el-table-column prop="isMature" label="成熟状态">
          <template #default="{ row }">
            <el-tag :type="row.isMature === '1' ? 'success' : 'warning'">
              {{ row.isMature === "1" ? "成熟" : "未成熟" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isPreorder" label="可预定">
          <template #default="{ row }">
            <el-tag :type="row.isPreorder ? 'success' : 'info'">
              {{ row.isPreorder ? "是" : "否" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isPest" label="病虫害">
          <template #default="{ row }">
            <el-tag :type="row.isPest === 1 ? 'danger' : 'success'">
              {{ row.isPest === 1 ? "有" : "无" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="180">
          <template #default="{ row, $index }">
            <el-link
              type="primary"
              :underline="false"
              style="margin-right: 10px"
              @click="onEdit(row, $index)"
              >编辑</el-link
            >
            <el-link
              type="primary"
              :underline="false"
              style="margin-right: 10px"
              @click="onView(row, $index)"
              >查看</el-link
            >
            <el-link
              type="danger"
              :underline="false"
              @click="onDelete(row, $index)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 新增/编辑弹窗 -->
      <el-dialog v-model="dialogVisible" :title="dialogTitle">
        <el-form :model="form" label-width="100px">
          <el-form-item label="作物名称">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="类别">
            <el-input v-model="form.cropCategory" />
          </el-form-item>
          <el-form-item label="所属土地">
            <el-input v-model="form.landName" />
          </el-form-item>
          <el-form-item label="价格">
            <el-input v-model.number="form.price" type="number" />
          </el-form-item>
          <el-form-item label="联系方式">
            <el-input v-model="form.phone" />
          </el-form-item>
          <el-form-item label="成熟状态">
            <el-select v-model="form.isMature">
              <el-option label="成熟" value="1" />
              <el-option label="未成熟" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="可预定">
            <el-select v-model="form.isPreorder">
              <el-option label="是" :value="true" />
              <el-option label="否" :value="false" />
            </el-select>
          </el-form-item>
          <el-form-item label="病虫害">
            <el-select v-model="form.isPest">
              <el-option label="有" :value="1" />
              <el-option label="无" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="作物图片">
            <el-input v-model="form.cropImage" placeholder="图片URL" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </template>
      </el-dialog>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next"
          :total="tableData.length"
          :page-size="10"
          :page-sizes="[10, 20, 50, 100]"
          v-model:current-page="currentPage"
        />
      </div>
    </el-card>
  </div>
</template>
<script setup lang='ts'>
import { ref, reactive, onMounted, computed } from "vue";
import { getAllCrop } from "../../api/farmer/crop";
import { CropInfoData, CropInfoItem } from "../../types/crop";
import { ElMessage } from "element-plus";

const tableData = ref<CropInfoItem[]>([]);
const filterCategory = ref("");
const filterMature = ref("");
const currentPage = ref(1);
const tableRef = ref();
const dialogVisible = ref(false);
const dialogTitle = ref("新增作物");
const form = reactive<CropInfoItem>({
  id: 0,
  name: "",
  phone: "",
  isMature: "0",
  cropImage: "",
  cropCategory: "",
  createTime: "",
  landName: "",
  price: 0,
  isPreorder: false,
  isPest: 0,
});
let editIndex = -1;

onMounted(async () => {
  await fetchCropData();
});

const fetchCropData = async () => {
  const res = await getAllCrop(1, 10);
  tableData.value = res.data.records.map((item) => {
    return {
      ...item,
      name: item.name.substring(0, item.name.length - 36),
      landName: item.landName.substring(0, item.landName.length - 36),
    };
  });
};

const filteredTableData = computed(() => {
  return tableData.value.filter((item) => {
    const matchCategory = filterCategory.value
      ? item.cropCategory === filterCategory.value
      : true;
    const matchMature = filterMature.value
      ? item.isMature === filterMature.value
      : true;
    return matchCategory && matchMature;
  });
});

const showAddCrop = () => {
  editIndex = -1;
  dialogVisible.value = true;
  dialogTitle.value = "新增作物";
  Object.assign(form, {
    id: 0,
    name: "",
    phone: "",
    isMature: "0",
    cropImage: "",
    cropCategory: "",
    createTime: "",
    landName: "",
    price: 0,
    isPreorder: false,
    isPest: 0,
  });
};

const onView = (row: CropInfoItem, index: number) => {
  dialogVisible.value = true;
  dialogTitle.value = "查看作物";
  Object.assign(form, row);
};

const onEdit = (row: CropInfoItem, index: number) => {
  dialogVisible.value = true;
  dialogTitle.value = "编辑作物";
  Object.assign(form, row);
  editIndex = index;
};

const onDelete = (row: CropInfoItem, index: number) => {
  tableData.value.splice(index, 1);
  ElMessage.success("删除成功");
};

const onSubmit = () => {
  if (editIndex === -1) {
    // 新增
    tableData.value.push({
      ...form,
      id: Date.now(),
      createTime: new Date().toISOString(),
    });
    ElMessage.success("新增成功");
  } else {
    // 编辑
    tableData.value[editIndex] = { ...form };
    ElMessage.success("编辑成功");
  }
  dialogVisible.value = false;
};
</script>
<style scoped lang='scss'>
.table-page {
  padding: 20px;
  background: #f5f6fa;
  min-height: 100vh;
}
.toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
